package com.chinar.funds;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.work.ExistingPeriodicWorkPolicy;
import androidx.work.OneTimeWorkRequest;
import androidx.work.PeriodicWorkRequest;
import androidx.work.WorkManager;

import com.chinar.funds.until.FundDatabaseHelper;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity implements com.chinar.funds.onViewClickListener {

    private EditText etFundCode;
    private Button btnAdd;
    private RecyclerView rvFunds;
    private TextView tvEmptyHint; // 添加空状态提示视图
    private com.chinar.funds.FundAdapter adapter;
    private FundDatabaseHelper dbHelper;
    private List<com.chinar.funds.Fund> fundList;
    private OkHttpClient client;
    private TextView workdayTextView;
    private TextView mainWellcomeTextView;
//    private Button itemDeleteButton;
    // 添加企业微信相关控件
    private Switch switchMessage;
    private EditText etWechatKey;
    private Button btnSaveKey;
    private Button btnTestSend; // 添加测试发送按钮

    private static final String API_URL = "https://fundgz.1234567.com.cn/js/"; // 基金信息API地址
    private static final String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Intent intent = getIntent();
        String username = intent.getStringExtra("username");
        String nickname = intent.getStringExtra("nickname");

        initViews(nickname);
//        setTitle("基金净值查询");
        getSupportActionBar().hide();
        dbHelper = new FundDatabaseHelper(this);
        client = new OkHttpClient();

        // 初始化 RecyclerView
        rvFunds.setLayoutManager(new LinearLayoutManager(this));
        fundList = new ArrayList<>();
        adapter = new com.chinar.funds.FundAdapter(fundList, this);
        rvFunds.setAdapter(adapter);

        // 加载数据库中的基金代码并请求数据
        loadAndFetchData();

        // 设置按钮点击事件
        btnAdd.setOnClickListener(v -> addFund());
        // itemDeleteButton的点击事件应该在适配器中处理，这里不需要设置
        // itemDeleteButton.setOnClickListener(v ->onDeleteClick(int position) );

        // 设置企业微信相关事件
        initWechatSettings();

        updateWorkdayText();

        // 启动定时刷新
        startAutoRefresh();

        // 设置定时发送消息任务（确保应用启动时注册定时任务）
        scheduleSendMessageTask();
    }

    private void initWechatSettings() {
        // 从数据库加载设置
        String wechatKey = dbHelper.getSetting("wechat_key", "c5abeaf8-f071-4759-b17e-9b2cfa9ee37c");
        boolean messageSwitch = Boolean.parseBoolean(dbHelper.getSetting("message_switch", "false"));

        // 设置UI
        etWechatKey.setText(wechatKey);
        switchMessage.setChecked(messageSwitch);

        // 保存按钮事件
        btnSaveKey.setOnClickListener(v -> {
            String key = etWechatKey.getText().toString().trim();
            if (!key.isEmpty()) {
                dbHelper.setSetting("wechat_key", key);
                Toast.makeText(this, "企业微信Key已保存", Toast.LENGTH_SHORT).show();
                Log.d(TAG, "企业微信Key已保存: " + key);

                // 更新定时任务
                scheduleSendMessageTask();
            } else {
                Toast.makeText(this, "请输入企业微信Key", Toast.LENGTH_SHORT).show();
            }
        });

        // 开关事件
        switchMessage.setOnCheckedChangeListener((buttonView, isChecked) -> {
            dbHelper.setSetting("message_switch", String.valueOf(isChecked));
            if (isChecked) {
                Toast.makeText(this, "消息推送已开启", Toast.LENGTH_SHORT).show();
                Log.d(TAG, "企业微信消息推送已开启");
            } else {
                Toast.makeText(this, "消息推送已关闭", Toast.LENGTH_SHORT).show();
                Log.d(TAG, "企业微信消息推送已关闭");
            }
        });
        
        // 测试发送按钮事件
        btnTestSend.setOnClickListener(v -> {
            // 检查开关状态
            boolean isMessageSwitchOn = Boolean.parseBoolean(dbHelper.getSetting("message_switch", "false"));
            if (!isMessageSwitchOn) {
                // 如果开关关闭，提醒用户
                new AlertDialog.Builder(this)
                    .setTitle("提示")
                    .setMessage("消息推送开关已关闭，测试消息将不会发送。请先打开开关。")
                    .setPositiveButton("打开开关", (dialog, which) -> {
                        // 打开开关并执行测试
                        switchMessage.setChecked(true);
                        dbHelper.setSetting("message_switch", "true");
                        executeTestSend();
                    })
                    .setNegativeButton("取消", null)
                    .show();
            } else {
                // 开关已打开，直接执行测试
                executeTestSend();
            }
        });
    }

    private void scheduleSendMessageTask() {
        Log.d(TAG, "设置定时发送消息任务");
        
        // 创建周期性工作任务，每15分钟执行一次（因为PeriodicWorkRequest的最短间隔是15分钟）
        PeriodicWorkRequest sendWork = new PeriodicWorkRequest.Builder(
                com.chinar.funds.SendMessageWorker.class, 15, TimeUnit.MINUTES)
                .build();

        // 添加任务到WorkManager
        WorkManager.getInstance(this).enqueueUniquePeriodicWork(
                "send_fund_message",
                ExistingPeriodicWorkPolicy.REPLACE,
                sendWork);
                
        Log.d(TAG, "定时发送消息任务已设置");
    }

    private void updateWorkdayText() {
        Date currentDate = new Date();

        // 定义日期格式
        SimpleDateFormat ymdFormat = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat ymFormat = new SimpleDateFormat("yyyy-MM");

        // 格式化当前日期
        String formattedDateYMD = ymdFormat.format(currentDate);
        String formattedDateYM = ymFormat.format(currentDate);

        // 设置默认文本
        workdayTextView.setText("检查中...");

        // 异步检查工作日
        isWorkday(formattedDateYM, formattedDateYMD, new WorkDay() {
            @Override
            public void isWorkday(boolean isWorkday) {
                runOnUiThread(() -> {
                    if (isWorkday) {
                        workdayTextView.setTextColor(Color.GREEN);
                        workdayTextView.setText("基金估值(今日开市)");
                    } else {
                        workdayTextView.setTextColor(Color.BLUE);
                        workdayTextView.setText("基金估值(今日休市)");
                    }
                });
            }
        });
    }

    private void isWorkday(String date, String day, WorkDay callback) {
        Request request = new Request.Builder()
                .url("https://www.szse.cn/api/report/exchange/onepersistenthour/monthList?month=" + date)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                if (response.isSuccessful()) {
                    String json = response.body().string();

                    try {
                        JSONObject jsonObject = new JSONObject(json);

                        // 获取 data 数组
                        if (jsonObject.has("data")) {
                            JSONArray dataArray = jsonObject.getJSONArray("data");

                            // 查找匹配的日期记录
                            for (int i = 0; i < dataArray.length(); i++) {
                                JSONObject record = dataArray.getJSONObject(i);

                                // 判断 jyrq 是否匹配
                                if (record.getString("jyrq").equals(day)) {
                                    String jybz = record.getString("jybz");
                                    if (jybz.equals("1")) {
                                        callback.isWorkday(true);
                                        return;
                                    } else {
                                        callback.isWorkday(false);
                                        return;
                                    }
                                }
                            }
                        }
                        callback.isWorkday(false);
                    } catch (JSONException e) {
                        e.printStackTrace();
                        callback.isWorkday(false);
                    }
                } else {
                    callback.isWorkday(false);
                }
            }

            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                e.printStackTrace();
                runOnUiThread(() -> {
                    workdayTextView.setText("检查失败");
                });
            }
        });
    }

    private void initViews(String nikename) {
        etFundCode = findViewById(R.id.et_fund_code);
        btnAdd = findViewById(R.id.btn_add);
        rvFunds = findViewById(R.id.rv_funds);
        tvEmptyHint = findViewById(R.id.tv_empty_hint); // 初始化空状态提示视图
        workdayTextView = findViewById(R.id.theday);
        mainWellcomeTextView=findViewById(R.id.main_wellcome_text);
        mainWellcomeTextView.setText(nikename+" 欢迎使用");
        // 初始化企业微信相关控件
        switchMessage = findViewById(R.id.switch_message);
        etWechatKey = findViewById(R.id.et_wechat_key);
        btnSaveKey = findViewById(R.id.btn_save_key);
        btnTestSend = findViewById(R.id.btn_test_send); // 初始化测试发送按钮
        
        // 设置企业微信Key输入框的跑马灯效果
        etWechatKey.setSelected(true);
    }

    private void loadAndFetchData() {
        List<String> codes = dbHelper.getAllFundCodes();
        fetchFundData(codes);
    }

    private void fetchFundData(List<String> codes) {
        fundList.clear();
        adapter.updateData(fundList); // 先清空并更新UI
        
        // 根据列表是否为空显示相应视图
        updateEmptyStateView();
        
        // 为每个代码创建一个新的临时列表来收集数据
        List<com.chinar.funds.Fund> tempFundList = new ArrayList<>();
        AtomicInteger pendingRequests = new AtomicInteger(codes.size());
        
        for (String code : codes) {
            fetchFundInfo(code, new FundDataCallback() {
                @Override
                public void onDataReceived(Fund fund) {
                    if (fund != null) {
                        // 检查是否已经存在于临时列表中
                        if (!tempFundList.contains(fund)) {
                            tempFundList.add(fund);
                        }
                    }
                    
                    // 当所有请求完成时，更新UI
                    if (pendingRequests.decrementAndGet() == 0) {
                        runOnUiThread(() -> {
                            fundList.clear();
                            fundList.addAll(tempFundList);
                            adapter.updateData(fundList);
                            
                            // 更新空状态视图
                            updateEmptyStateView();
                        });
                    }
                }
                
                @Override
                public void onError(String code) {
                    // 即使出错也减少计数器
                    if (pendingRequests.decrementAndGet() == 0) {
                        runOnUiThread(() -> {
                            fundList.clear();
                            fundList.addAll(tempFundList);
                            adapter.updateData(fundList);
                            
                            // 更新空状态视图
                            updateEmptyStateView();
                        });
                    }
                }
            });
        }
        
        // 如果没有基金代码，确保更新空状态视图
        if (codes.isEmpty()) {
            updateEmptyStateView();
        }
    }

    // 添加更新空状态视图的方法
    private void updateEmptyStateView() {
        if (fundList.isEmpty()) {
            rvFunds.setVisibility(View.GONE);
            tvEmptyHint.setVisibility(View.VISIBLE);
        } else {
            rvFunds.setVisibility(View.VISIBLE);
            tvEmptyHint.setVisibility(View.GONE);
        }
    }

    private void fetchFundInfo(String code, FundDataCallback callback) {
        Request request = new Request.Builder()
                .url(API_URL + code + ".js?rt=" + System.currentTimeMillis())
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    String jsonpData = response.body().string();
                    int firstParenthesis = jsonpData.indexOf('(');
                    int lastParenthesis = jsonpData.lastIndexOf(')');
                    if (firstParenthesis != -1 && lastParenthesis != -1 && lastParenthesis > firstParenthesis) {
                        String json = jsonpData.substring(firstParenthesis + 1, lastParenthesis);
                        try {
                            JSONObject jsonObject = new JSONObject(json);
                            
                            // 检查必要的字段是否存在
                            if (jsonObject.has("fundcode") && jsonObject.has("name") && 
                                jsonObject.has("gsz") && jsonObject.has("dwjz")) {
                                Fund fund = new Fund(
                                        jsonObject.getString("fundcode"),
                                        jsonObject.getString("name"),
                                        jsonObject.getString("gsz"),
                                        jsonObject.getString("dwjz")
                                );
                                callback.onDataReceived(fund);
                            } else {
                                runOnUiThread(() ->
                                        Toast.makeText(MainActivity.this, "基金 " + code + " 数据不完整", Toast.LENGTH_SHORT).show()
                                );
                                callback.onError(code);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                            runOnUiThread(() ->
                                    Toast.makeText(MainActivity.this, "解析基金 " + code + " 数据失败", Toast.LENGTH_SHORT).show()
                            );
                            callback.onError(code);
                        }
                    } else {
                        runOnUiThread(() ->
                                Toast.makeText(MainActivity.this, "基金 " + code + " 数据格式错误", Toast.LENGTH_SHORT).show()
                        );
                        callback.onError(code);
                    }
                } else {
                    runOnUiThread(() ->
                            Toast.makeText(MainActivity.this, "获取基金 " + code + " 数据失败", Toast.LENGTH_SHORT).show()
                    );
                    callback.onError(code);
                }
            }

            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                runOnUiThread(() ->
                        Toast.makeText(MainActivity.this, "获取基金 " + code + " 数据失败", Toast.LENGTH_SHORT).show()
                );
                callback.onError(code);
            }
        });
    }

    private void checkFundExists(String code, FundCheckCallback callback) {
        Request request = new Request.Builder()
                .url(API_URL + code + ".js")
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    String jsonpData = response.body().string();
                    // 检查返回数据是否包含错误信息
                    if (jsonpData.contains("错误")) {
                        callback.onResult(false);
                    } else {
                        // 尝试解析数据以确认基金是否存在
                        int firstParenthesis = jsonpData.indexOf('(');
                        int lastParenthesis = jsonpData.lastIndexOf(')');
                        if (firstParenthesis != -1 && lastParenthesis != -1 && lastParenthesis > firstParenthesis) {
                            String json = jsonpData.substring(firstParenthesis + 1, lastParenthesis);
                            try {
                                new JSONObject(json); // 尝试解析JSON
                                callback.onResult(true);
                            } catch (JSONException e) {
                                callback.onResult(false);
                            }
                        } else {
                            callback.onResult(false);
                        }
                    }
                } else {
                    callback.onResult(false);
                }
            }

            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                callback.onResult(false);
            }
        });
    }

    private void addFund() {
        String code = etFundCode.getText().toString().trim();
        if (code.isEmpty()) {
            Toast.makeText(this, "请输入基金代码", Toast.LENGTH_SHORT).show();
            return;
        }

        if (dbHelper.isFundExists(code)) {
            Toast.makeText(this, "该基金已存在", Toast.LENGTH_SHORT).show();
        } else {
            checkFundExists(code, new FundCheckCallback() {
                @Override
                public void onResult(boolean exists) {
                    if (exists) {
                        if (dbHelper.insertFund(code)) {
                            runOnUiThread(() -> {
                                Toast.makeText(MainActivity.this, "添加成功", Toast.LENGTH_SHORT).show();
                                etFundCode.setText("");
                                loadAndFetchData(); // 重新加载并获取数据
                            });
                        } else {
                            runOnUiThread(() ->
                                    Toast.makeText(MainActivity.this, "添加失败", Toast.LENGTH_SHORT).show()
                            );
                        }
                    } else {
                        runOnUiThread(() ->
                                Toast.makeText(MainActivity.this, "基金代码不存在", Toast.LENGTH_SHORT).show()
                        );
                    }
                }
            });
        }
    }

    private void startAutoRefresh() {
        new Timer().scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                Calendar calendar = Calendar.getInstance();
                int hour = calendar.get(Calendar.HOUR_OF_DAY);
                int minute = calendar.get(Calendar.MINUTE);
                int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
                
                // 判断是否为工作日（周一到周五）
                boolean isWeekday = dayOfWeek >= Calendar.MONDAY && dayOfWeek <= Calendar.FRIDAY;
                
                // 判断时间是否在上午9点到下午15点之间
                boolean isTradingHours = hour >= 9 && hour < 15;
                
                if (isWeekday && isTradingHours) {
                    runOnUiThread(() -> loadAndFetchData());
                }
            }
        }, 0, 60000); // 每 60 秒执行一次
    }

    @Override
    public void onClick(int position) {
        // 获取被点击的 Fund 数据
        com.chinar.funds.Fund clickedFund = fundList.get(position);

        // 跳转到详情页，并传递数据
        Intent intent = new Intent(this, com.chinar.funds.FundDetailActivity.class);
        intent.putExtra("fund", clickedFund);
        startActivity(intent);
    }

    @Override
    public void onDeleteClick(int position) {
        // 显示删除确认对话框
        showDeleteConfirmationDialog(position);
    }

    private void showDeleteConfirmationDialog(int position) {
        com.chinar.funds.Fund fundToDelete = fundList.get(position);
        
        new AlertDialog.Builder(this)
                .setTitle("确认删除")
                .setMessage("确定要删除基金 " + fundToDelete.getName() + " (" + fundToDelete.getCode() + ") 吗？")
                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 用户确认删除
                        deleteFund(position);
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 用户取消删除，关闭对话框
                        dialog.dismiss();
                    }
                })
                .show();
    }

    private void deleteFund(int position) {
        // 删除基金
        com.chinar.funds.Fund fundToDelete = fundList.get(position);
        String fundCode = fundToDelete.getCode();
        dbHelper.deleteFund(fundCode);
        fundList.remove(position);
        adapter.updateData(fundList);
        Toast.makeText(this, "已删除基金 " + fundCode, Toast.LENGTH_SHORT).show();
        
        // 更新空状态视图
        updateEmptyStateView();
    }

    /**
     * 执行测试发送任务
     */
    private void executeTestSend() {
        // 创建一个一次性工作任务用于测试（忽略时间限制）
        OneTimeWorkRequest testWork = new OneTimeWorkRequest.Builder(SendMessageWorker.class)
                .setInputData(new androidx.work.Data.Builder().putString("is_test", "true").build())
                .build();
        WorkManager.getInstance(this).enqueue(testWork);
        Toast.makeText(this, "已触发测试发送任务，请查看企业微信是否收到消息", Toast.LENGTH_LONG).show();
        Log.d(TAG, "测试发送任务已触发");
    }

    // 回调接口用于检查基金是否存在
    interface FundCheckCallback {
        void onResult(boolean exists);
    }

    interface WorkDay {
        void isWorkday(boolean isWorkday);
    }
    
    // 添加基金数据回调接口
    interface FundDataCallback {
        void onDataReceived(Fund fund);
        void onError(String code);
    }
}
